package com.jdk.demo.thread.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BiFunction;

// handle 是执行任务完成时对结果的处理。
//handle 方法和 thenApply 方法处理方式基本一样。不同的是 handle 是在任务完成后再执行，还可以处理异常的任务。thenApply 只可以执行正常的任务，任务出现异常则不执行 thenApply 方法
public class HandleDemo {

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(2);
		CompletableFuture cf = CompletableFuture.supplyAsync(() -> { // 实现了Supplier的get()方法
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("supplyAsync " + Thread.currentThread().getName());
			return 100;
		}, executorService)
		.handle(new BiFunction<Integer, Throwable, Integer>() {
			@Override
			public Integer apply(Integer param, Throwable throwable) {
				int result = -1;
				if (throwable == null) {
					result = param * 2;
				} else {
					System.out.println(throwable.getMessage());
				}
				return result;
			}
		});

		System.out.println(Thread.currentThread().getName());
		while (true) {
			if (cf.isDone()) {
				System.out.println("CompletedFuture...isDown " + Thread.currentThread().getName());
				break;
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
